<template>
  <div id="index">
    <div class="index-top">
      <div class="top_btn" @click="sendCV">
        去投递
      </div>
    </div>
    <div class="bottom">
      <div class="inner">
        <div class="items-wrap">
          <div class="items" :class="[item.disabled ? 'disabled-style' : '']" v-for="(item, idx) in list"
            :key="item.label" @click="openModal(item)">
            <img :src="getImageUrl(`item-${idx + 1}.png`, 'index')" alt="" srcset="" />
            <span class="label">{{ item.label }}</span>
          </div>
          <div class="send-btn" @click="sendCV">
            <span>简历投递</span>
          </div>
        </div>
        <div class="reason-title">加入方田的N个理由</div>
        <div class="reason-wrap">
          <swiper :modules="swiperOptions.modules" :slides-per-view="swiperOptions.slidesPerView"
            :space-between="swiperOptions.spaceBetween" :pagination="swiperOptions.pagination">
            <swiper-slide v-for="(item, index) in swpierList" :key="item.label">
              <div class="slide-content">
                <div class="prise">
                  <img src="../../assets/img/index/prise.png" alt="" srcset="">
                  <h2>No.{{ index + 1 }}</h2>
                </div>
                <p>{{ item.label }}</p>
                <img :src="getImageUrl(`reason-${index + 1}.png`, 'index')" alt=""></img>
              </div>
            </swiper-slide>
            <div class="swiper-pagination"></div>
          </swiper>
        </div>
      </div>
      <Footer></Footer>
    </div>
  </div>
  <commonModal ref="myModal" :title="title">
    <template #default v-if="userIndexStatusMap.trainingStatus == 2">
      <TrainModal @item-click="itemClick"></TrainModal>
    </template>
    <template v-else #default>
      <CommonForm :formList='formList' :myModal="myModal" :form="form" @doSubmit="doSubmit"></CommonForm>
    </template>
  </commonModal>
  <VolunteerChoose ref="volunteerRef" @refresh="refresh"></VolunteerChoose>
  <ConfirmModal :identifier="'train'" ref="modal"></ConfirmModal>

  <commonModal ref="listModal" title="饮食调查">
    <template #default>
      <MealsModal @cancel="listModal.show = false" :mealsMap='mealsMap' @confirm="confirm"></MealsModal>
    </template>
  </commonModal>

  <FinishModal v-if="showFinishModal" @closeFinishModal="showFinishModal = false">
  </FinishModal>


  <a-modal v-model:open="open" title="培训协议预览" width="100%" wrap-class-name="full-modal">
    <div class="modal-wrap">
      <img :src="userIndexStatusMap.trainingUrl" alt="" srcset="">
    </div>
  </a-modal>
</template>

<script setup lang="ts">

import ConfirmModal from '../join/ConfirmModal.vue';
import Footer from '@/components/Footer.vue';
// import Swiper core and required modules
import { Pagination } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/vue';
import commonModal from "./commonModal.vue"
import CommonForm from '@/components/CommonForm.vue';
import VolunteerChoose from '../volunteer/VolunteerChoose.vue';
import TrainModal from './TrainModal.vue';
import MealsModal from './MealsModal.vue';
import { getImageUrl } from '@/assets/common';
import { IndexFormItem } from "./type";
import apis from "../../api/index.ts"
const { userResumesList, userResumesProcess, userIndexStatus, selectCommonConfigDetail, selectTrainingNumberList, joinTrainingNumber } = apis
import 'swiper/scss';
import 'swiper/scss/pagination';
import { formItem } from '../join/data';
import router from '@/routers';
import { useStore } from "../../store/index.ts"
import { message } from 'ant-design-vue';
import FinishModal from './FinishModal.vue';
const store = useStore();
const { userInfo } = store as any;
interface ModalForm {
  name: string
  id: number | string
  cardType: string
  date: string
}
interface ListItem {
  label: string;
  url: string;
  img: string;
  id: number | string,
  disabled?: boolean
}
const swiperOptions = ref<any>({
  slidesPerView: 3,
  spaceBetween: 30,
  pagination: {
    clickable: true,
    el: '.swiper-pagination',
  },
  modules: [Pagination]
});
interface ResumeInfo {
  trainingStatus?: number | string
  volunteerStatus?: number | string
  volunteerTime?: any
  userName?: string
  sex?: any
  certificateType?: string
  certificateNumber?: string
  resumesId?: number
  trainingNumberId?: string | number
  trainingUrl?: string
  notEat?: string
  taste?: string
  resumesStatus?: number
}
const userIndexStatusMap = ref<ResumeInfo>({ trainingStatus: null, volunteerStatus: null });  //用户首页 展示状态
const userResumesListMap = ref([]);  //用户投递简历列表
const userResumesProcessMap = ref({})
const list = ref<ListItem[]>([
  { label: '应聘进度', url: '/progress', img: '', id: 1, disabled: false },
  { label: '参培确认', url: '', img: '', id: 2, disabled: false },
  { label: '志愿选择', url: '/', img: '', id: 3, disabled: false },
]);

const swpierList = ref([
  {
    label: '迅猛的发展速度：学生规模在10年内实现了100人次至15万人次的增长',
  },
  {
    label: '广阔的晋升空间：教师岗管理层平均年龄26.6岁，所有员工平均年龄25岁，每年两次晋升机会',
  },
  {
    label: '优秀的教师团队：老师基本毕业于国内知名高校，让最优秀的人进入教育行业，与优秀同行',
  },
  {
    label: '稳定的高薪待遇：教师岗位平均工资18.6万，每人每年6次涨薪机会',
  },
]);
interface Options {
  label: string
  value: string
}

const getCommonConfigDetail = async (key: string): Promise<Options[]> => {
  const data: any = await selectCommonConfigDetail({ type: key });
  let list: Options[] = [];
  list = data.data.map((el) => {
    return {
      label: el.label,
      value: el.label,
    };
  });
  formList.value[1].options = list
  return list
}
function transformData(data) {
  return data.map(yearData => ({
    value: yearData.dateTime,
    label: yearData.dateTime,
    children: yearData.monthList.map(monthData => ({
      value: monthData.dateTime,
      label: monthData.dateTime,
      children: monthData.numberList.map(numberData => ({
        value: numberData.trainingNumberId,
        trainingYearTime: numberData.trainingYearTime,
        trainingMonthTime: numberData.trainingMonthTime,
        number: numberData.number,
        label: numberData.startTimeEndTime
      }))
    }))
  }));
}

const getTrainingNumberList = async () => {
  const data: any = await selectTrainingNumberList();
  if (data && data.code == '10000') {
    console.log(data.data, '===>data')
    let list = transformData(data.data);
    formList.value[2].options = list
  } else {
    message.error(data.msg)

  }
}

getCommonConfigDetail("CERTIFICATE");
getTrainingNumberList();

const formList = ref<IndexFormItem[]>([
  { label: "姓名", name: "name", value: "", disabled: true, component: 'input' },
  {
    label: "证件号码", name: "idCard", value: [], disabled: true, component: "assembly",
    options: [],
    errorMsg: "请输入正确的证件号码",
  },
  {
    label: "参培时间", name: "date", value: [], component: "cascader",
    errorMsg: "请选择参培时间",
    options: [],
    tip: '每人仅允许选择一次参培时间，提交成功后无法自助修改。如确有修改需求，请将修改原因发送到ftzhaopin@fangtian.me邮箱说明，或及时与对应HR沟通。'
  },

])
formList.value.forEach((el: IndexFormItem) => {
  el.showError = false
})

const form = ref<ModalForm>({
  id: "",
  name: "",
  date: "",
  cardType: ''
});
const myModal = ref<any>();
const title = ref<string>('');
const showFinishModal = ref<boolean>(false);

const volunteerRef = ref<typeof VolunteerChoose>(VolunteerChoose)

const openModal = (item: ListItem) => { //打开参培确认，应聘进度 志愿选择模态框
  const { trainingStatus, volunteerStatus } = userIndexStatusMap.value;
  if (item.id === 1) {
    router.push(
      {
        path: '/progress',
        query: userResumesProcessMap.value
      }
    )
  } else if (item.id === 2) {
    if (item.disabled) {
      message.error('暂未开放~')
      return false
    }
    if (trainingStatus == 2) {
      //已经填过协议了
      title.value = "培训相关"
    }
    title.value = item.label
    myModal.value.show = true
  } else if (item.id === 3) {
    //支援选择
    if (item.disabled) {
      message.error('暂未开放~')
      return false
    }
    // volunteerRef.value.show()
    if (volunteerStatus === 1) {
      volunteerRef.value.show()
    } else if (volunteerStatus === 2) {
      showFinishModal.value = true
    }
  }
}


const getUserResumesList = async () => {
  const data: any = await userResumesList({ userId: userInfo.userId });
  console.log(data, 'getUserResumesList')
  if (data && data.code === '10000') {
    userResumesListMap.value = data.data
  } else {
    message.error(data.msg)
  }
}
const getUserResumesProcess = async () => {
  const { resumesId } = userIndexStatusMap.value
  if (!resumesId) return;
  const data: any = await userResumesProcess({ resumesId: resumesId });
  console.log(data, 'getUserResumesProcess');
  if (data && data.code === '10000') {
    userResumesProcessMap.value = data.data;
    store.$patch({ resumeProcess: userResumesProcessMap.value })
  } else {
    message.error(data.msg)
  }
}

const getUserIndexStatus = async () => {
  const data: any = await userIndexStatus({ userId: userInfo.userId });
  console.log(data, 'getserIndexStatus');
  if (data && data.code === '10000') {
    userIndexStatusMap.value = data.data;
    store.$patch({ //存储简历信息
      resumeInfo: userIndexStatusMap.value
    })
    const { taste, notEat } = userIndexStatusMap.value;
    mealsMap.value.meals = taste
    mealsMap.value.diet = notEat
    list.value[1].disabled = !userIndexStatusMap.value.trainingStatus
    list.value[2].disabled = !userIndexStatusMap.value.volunteerStatus
    const { userName, certificateType, certificateNumber } = userIndexStatusMap.value
    formList.value[0].value = userName
    formList.value[1].value = [certificateType, certificateNumber]
  } else {
    message.error(data.msg)
  }

}
const route = useRoute();
onMounted(async () => {
  //console.log(userInfo.phone)
  if (userInfo.phone != undefined) {
    refresh()
  }
  //判定是不是从id=2来的
  // if (route.query.id == "2") {
  //   title.value = "参培确认"
  //   myModal.value.show = true
  // }
})
const refresh = async () => {
  //getUserResumesList();
  await getUserIndexStatus();
  getUserResumesProcess();
}

const doSubmit = async (val: formItem[]) => {
  console.log(val[2]);
  let timeRange = ""
  val[2].options.forEach(a => {
    a.children.forEach(b => {
      b.children.forEach(c => {
        if (val[2].value[0] == a.value && val[2].value[1] == b.value && val[2].value[2] == c.value) {
          timeRange = c.label
        }
      })
    })
  });

  const trainingNumberId = val[2].value[2];

  const resumesId = userIndexStatusMap.value.resumesId;
  router.push(
    {
      path: "/trainAgreement",
      query: {
        resumesId,
        trainingNumberId,
        timeRange
      }
    }
  );

}
const modal = ref<typeof ConfirmModal>(ConfirmModal)
const sendCV = () => {
  const { resumesStatus } = userIndexStatusMap.value
  if (resumesStatus === 1) {
    modal.value.show() //如果已经投递了，则弹框
  } else {
    // 否则跳转
    router.push('/join')
  }

}

const listModal = ref<any>(null)
const getFile = () => {
  return new URL(`/src/assets/file/a.pdf`, import.meta.url).href;
}
const open = ref<boolean>(false)
const itemClick = (val) => {
  if (val.key == 'meals') {
    //饮食
    listModal.value.show = true
    myModal.value.show = false
  } else if (val.key == 'refund') {
    //报销
    const url = getFile();
    window.open(url)
    myModal.value.show = false
  } else {
    //签约协议
    open.value = true;
    router.push('/trainAgreementPrivew')
  }

}

const mealsMap = ref<any>({})
const confirm = async (val) => {  //确认饮食调查
  if (mealsMap.value.meals) {
    listModal.value.show = false
    return
  }
  const { resumesId, trainingNumberId, trainingUrl } = userIndexStatusMap.value
  const { diet, meals } = val
  const data: any = await joinTrainingNumber({ trainingNumberId, resumesId, trainingUrl, notEat: diet, taste: meals, 'editType': 1 });
  if (data && data.code === '10000') {
    message.success('填写成功');
    listModal.value.show = false
    refresh()
  } else {
    message.error(data.msg)
  }
}
</script>
<style lang="scss" scoped>
@import 'swiper/scss';


#index {
  width: 100vw;
  display: flex;
  flex-direction: column;

  :deep(.swiper.swiper-initialized.swiper-horizontal) {
    padding-bottom: 40px;
  }

  .swiper-pagination {
    bottom: 0%;
  }

  :deep(.swiper-pagination-bullet.swiper-pagination-bullet-active) {
    width: 20px;
    height: 8px;
    border-radius: 10px;
    background-color: #209EE4;
  }

  .index-top {
    position: relative;
    width: 100vw;
    height: 100vh;
    background: url('../../assets/img/index/index-bg.png') no-repeat;

    .top_btn {
      position: absolute;
      bottom: 130px;
      left: 45%;
      width: 150px;
      height: 50px;
      background: rgba(32, 158, 228, 0.5);
      backdrop-filter: blur(20px);
      border-radius: 48px 48px 48px 48px;
      text-align: center;
      line-height: 50px;
      color: #fafafa;
      cursor: pointer;

      &:hover {
        background: rgba(32, 158, 228, 0.6);
        backdrop-filter: blur(10px);
        color: #ffffff;
      }
    }
  }

  .bottom {
    width: 100%;
    height: 882px;

    .inner {
      width: calc(100vw - 720px);
      margin: 0 auto;
      height: 760px;
      padding-top: 40px;
      box-sizing: border-box;

      .items-wrap {
        display: flex;
      }

      .items {
        width: 260px;
        height: 120px;
        background: #ffffff;
        border-radius: 20px 20px 20px 20px;
        border: 2px solid #fff;
        margin-right: 17px;
        display: flex;
        position: relative;
        align-items: center;
        padding-left: 18px;
        box-sizing: border-box;
        cursor: pointer;

        &:hover {
          color: #209ee4;
          box-shadow: 0px 0px 8px 0px rgba(7, 33, 67, 0.15);
        }

        img {
          width: 108px;
          height: 120px;
          position: absolute;
          right: 0;
          top: 0;
        }
      }

      .send-btn {
        width: 370px;
        height: 120px;
        background: url("../../assets/img/index/promotion.png");
        font-size: 16px;
        line-height: 120px;
        color: #fff;
        cursor: pointer;

        span {
          margin-left: 96px;
        }
      }

      .reason-title {
        font-weight: 600;
        font-size: 32px;
        color: #333333;
        line-height: 38px;
        text-align: left;
        margin: 40px 0;
      }

      .reason-wrap {
        .slide-content {
          width: 385px;
          height: 385px;
          background: url("../../assets/img/index/reason-bg.png");
          box-sizing: border-box;
          padding: 62px 12px 22px 18px;
          position: relative;

          .prise {
            position: absolute;
            left: 18px;
            top: 8px;
            display: flex;
            justify-content: center;
            align-items: center;

            img {
              width: 24px;
              height: 24px;
              margin-right: 6px
            }

            h2 {
              font-size: 18px;
              color: #fff;
            }
          }

          p {
            height: 100px;
            margin-top: 10px;
          }

          img {
            width: 350px;
          }
        }
      }
    }
  }
}

.disabled-style {
  /*pointer-events: none;*/
  cursor: not-allowed !important;

  img {
    //filter: grayscale(1);
    opacity: 0.3;
  }

  span {
    color: #7A8690;
  }

  &:hover {
    cursor: not-allowed !important;
  }
}

.modal-wrap {
  width: 1200px;
  height: 90vh;
  overflow-y: auto;
  margin: 0 auto;

  img {
    width: 100%;
  }
}
</style>
